<template>
    <el-dialog v-model="openDirectoryVisible" title="选择目录" align-center :before-close="handleBeforeClose"
        class="directory-dialog">
        <div v-if="step === 0" class="directory-selected-wrapper">
            <div class="directory-toolbar">
                <div class="directory-toolbtn" @click="onClickHome">
                    <HomeFilled class="directory-toolbtn-icon" />
                </div>
                <div class="directory-toolbtn" @click="onClickUp">
                    <Top class="directory-toolbtn-icon" />
                </div>
            </div>
            <el-input v-model="tmp_dir" class="directory-selected" @keyup.enter="onInputEnter"></el-input>
        </div>
        <div v-if="step === 0" class="directory-panel">
            <div class="directory-content-wrapper">
                <div class="directory-root-item">
                    <Management class="directory-item-title-icon yellow" />
                    <div class="directory-item-title">{{ dataset_dir }}</div>
                </div>
                <div v-for="(subdir, index) in sub_dirs" :key="index" class="directory-item"
                    @dblclick="onDbClickSubDir(subdir)">
                    <Ticket class="directory-item-icon yellow" />
                    <div>{{ subdir }}</div>
                </div>
            </div>
        </div>
        <div v-if="step === 1" v-loading="loading" element-loading-text="分析格式中..." class="dataset-property-panel">
            <div class="directory-labeltype-wrapper">
                <div class="dataset-property-key">目录</div>
                <el-tooltip placement="bottom" :content="dataset_dir">
                    <div class="dataset-property-value">{{ dataset_dir }}</div>
                </el-tooltip>
            </div>
            <div class="directory-labeltype-wrapper">
                <div class="dataset-property-key">格式</div>
                <el-select class="dataset-property-value" style="padding: 0px" v-model="label_format"
                    placeholder="请选择标注格式">
                    <el-option v-for="format in formats" :label="format" :value="format" />
                </el-select>
            </div>
            <div v-if="label_files.length > 0" class="dataset-label-files-wrapper">
                <div class="dataset-label-files-title">请选择标注文件</div>
                <el-table class="dataset-label-files" :data="label_files" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column property="file" label="标注文件" show-overflow-tooltip />
                </el-table>
            </div>
        </div>
        <template #footer>
            <span>
                <el-button type="primary" @click="onDirectoryConfirm(true)"> {{ step == 0 ? '下一步' : '导入数据' }}
                </el-button>
                <el-button @click="onDirectoryConfirm(false)">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import API from '@/js/api';
import { ElMessage } from 'element-plus';
import { onMounted, ref, watch, inject, toRaw } from 'vue';
import { getParentPath } from '@/js/utils/fileUtils';

const emit = defineEmits(['directoryConfirm']);
const props = defineProps(['openDirectoryVisible']);
let vueApp = inject('vueApp');

// 定义vue变量
const openDirectoryVisible = ref(false);
const dataset_dir = ref('');
const tmp_dir = ref('');
const sub_dirs = ref([]);
const step = ref(0);
const loading = ref(false);

const formats = ref([]);
const label_format = ref('voc');
const label_files = ref([]);
const label_selections = ref([]);

watch(
    () => dataset_dir.value,
    async (newValue, oldValue) => {
        // console.log(`dataset_dir newValue = `, newValue);
        let result = await getSubDirectories(newValue);
        if (!result) {
            ElMessage.error(`目录${newValue}不存在`);
            let result = await API.invoke('GetRootDirectory');
            if (result.code == 0) {
                dataset_dir.value = result.msg;
                tmp_dir.value = result.msg;
            }
        }
    }
);

watch(
    () => props.openDirectoryVisible,
    (newVisible, oldVisible) => {
        openDirectoryVisible.value = props.openDirectoryVisible;
        vueApp.monitorKeyEvent(!props.openDirectoryVisible);
        if (newVisible) {
            getRootDirectories();
        }
    }
);

async function onDirectoryConfirm(confirm) {
    const machine = vueApp.getMachine();
    if (confirm) {
        localStorage.setItem(`openDirectory-${machine}`, dataset_dir.value);
        if (step.value == 0) {
            step.value = 1;
            loading.value = true;
            let algo_type = vueApp.getAlgoType();
            // console.log('algo_type = ', algo_type);
            let result = await API.invoke('GetDatasetFormat', {
                dataset_supertype: algo_type.supertype,
                dataset_type: algo_type.type,
                dataset_dir: dataset_dir.value
            });
            loading.value = false;

            // console.log(result);
            if (result.code == 0) {
                formats.value = result.msg.formats;
                label_format.value = result.msg.format;
                label_files.value = result.msg.labels.map((item) => {
                    return { file: item };
                });
                label_selections.value = [];
            } else {
                step.value = 0;
            }
        } else {
            emit('directoryConfirm', {
                dataset_dir: dataset_dir.value,
                label_format: label_format.value,
                label_selections: toRaw(label_selections.value)
            });
            step.value = 0;
        }
    } else {
        emit('directoryConfirm', null);
        step.value = 0;
    }
}

function handleSelectionChange(selections) {
    // console.log('handleSelectionChange selections = ', selections);
    label_selections.value = selections.map((item) => {
        return item.file;
    });
}

function handleBeforeClose() {
    vueApp.monitorKeyEvent(true);
    emit('directoryConfirm', null);
    step.value = 0;
}

async function getRootDirectories() {
    const machine = vueApp.getMachine();
    const openDirectory = localStorage.getItem(`openDirectory-${machine}`);
    // console.log('openDirectory = ', openDirectory);

    if (!openDirectory) {
        try {
            let result = await API.invoke('GetRootDirectory');
            if (result.code == 0) {
                dataset_dir.value = result.msg;
                tmp_dir.value = result.msg;
            } else {
                dataset_dir.value = '';
                tmp_dir.value = result.msg;
            }
        } catch (error) { }
    } else {
        dataset_dir.value = openDirectory;
        tmp_dir.value = openDirectory;
    }
}

async function getSubDirectories(rootDir) {
    let result = await API.invoke('GetSubDirectories', { directory: rootDir });
    if (result && result.code == 0) {
        sub_dirs.value = result.msg;
        return true;
    } else {
        return false;
    }
}

async function onDbClickSubDir(subdir) {
    let result = await API.invoke('PathJoin', { dirs: JSON.stringify([dataset_dir.value, subdir]) });
    if (result.code == 0) {
        dataset_dir.value = result.msg;
        tmp_dir.value = result.msg;
    } else {
        ElMessage.error(`获取子目录${subdir}失败!`);
    }
}

function onInputEnter() {
    dataset_dir.value = tmp_dir.value;
}

function onClickHome() {
    getRootDirectories();
}

function onClickUp() {
    let path = getParentPath(dataset_dir.value);
    dataset_dir.value = path;
    tmp_dir.value = path;
}

onMounted(() => {
    getRootDirectories();
});
</script>

<style scoped>
.directory-dialog {
    display: block;
}

.directory-dialog .directory-panel {
    background-color: rgb(255, 255, 255);
    width: 100%px;
    height: 250px;
    overflow: auto;
    border: solid 1px;
    border-color: #cfcfcf;
}

.directory-dialog .el-dialog__body {
    margin: 10px 20px;
    padding: 0px;
}

.directory-content-wrapper {
    display: block;
    background-color: rgb(253, 253, 253);
    width: 100%;
    height: calc(100% - 0px);
}

.directory-root-item {
    display: flex;
    font-size: 14px;
    padding: 10px 5px 10px 10px;
    color: rgb(66, 66, 67);
    background-color: rgb(255, 255, 255);
    cursor: default;
}

.directory-root-item:hover {
    background-color: rgb(235, 235, 235);
}

.directory-item {
    position: relative;
    display: flex;
    background-color: rgb(255, 255, 255);
    padding: 10px 25px 10px 40px;
    font-size: 14px;
    color: rgb(66, 66, 67);
    cursor: default;
}

.directory-item:hover {
    background-color: rgb(235, 235, 235);
}

.directory-item-title {
    padding-right: 80px;
}

.directory-item-title-icon {
    padding: 0px 5px 0px 0px;
    width: 16px;
    height: 16px;
    color: rgb(66, 66, 67);
}

.directory-item-title-icon.yellow {
    color: rgb(223, 173, 36);
}

.directory-item-icon {
    padding: 0px 5px 0px 0px;
    width: 16px;
    height: 16px;
    color: rgb(66, 66, 67);
}

.directory-item-icon.yellow {
    color: rgb(223, 173, 36);
}

.directory-selected-wrapper {
    display: flex;
    margin: 3px 0px 8px 0px;
}

.directory-labeltype-wrapper {
    display: flex;
    margin: 8px 0px 5px 0px;
}

.directory-selected-title {
    width: 70px;
    padding: 5px;
}

.directory-selected {
    height: 32px;
    margin-left: 4px;
}

.directory-toolbar {
    display: flex;
    width: 70px;
    background-color: rgb(255, 255, 255);
}

.directory-toolbtn {
    width: 30px;
    height: 30px;
    margin: 0px 2px;
    border: solid 1px;
    border-color: #e1e1e1;
}

.directory-toolbtn-icon {
    width: 18px;
    height: 18px;
    margin: 6px 6px;
    font-weight: bold;
}

.directory-toolbtn:hover {
    background-color: #ece9e9;
    cursor: pointer;
}

.dataset-property-panel .el-loading-mask {
    z-index: 9;
}

.dataset-property-key {
    width: 60px;
    padding: 8px;
    box-sizing: border-box;
}

.dataset-property-value {
    padding: 8px;
    width: calc(100% - 60px);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.dataset-label-files-wrapper {
    padding: 5px;
}

.dataset-label-files-title {
    margin-top: 10px;
    padding-left: 3px;
}

.dataset-label-files {
    border: 1px solid rgb(219, 219, 219);
    margin-top: 10px;
    box-sizing: border-box;
}
</style>
